/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/11/25 09:31
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

(function () {

    "use strict";

    var shopModule = angular.module('wxModule', ['ngSanitize']);
    shopModule.config(function ($httpProvider) {

        /**
         * 支持 form data 格式的数据 POST
         */
        $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
        $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';

        /**
         * 重写angular的param方法，使angular使用jquery一样的数据序列化方式
         * The workhorse; converts an object to x-www-form-urlencoded serialization.
         *
         * @param {Object} obj
         * @return {String}
         */
        var param = function (obj) {
            var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

            for (name in obj) {
                value = obj[name];

                if (value instanceof Array) {
                    for (i = 0; i < value.length; ++i) {
                        subValue = value[i];
                        fullSubName = name + '[' + i + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                    }
                }
                else if (value instanceof Object) {
                    for (subName in value) {
                        subValue = value[subName];
                        fullSubName = name + '[' + subName + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                    }
                }
                else if (value !== undefined && value !== null)
                    query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
            }

            return query.length ? query.substr(0, query.length - 1) : query;
        };

        // Override $http service's default transformRequest
        $httpProvider.defaults.transformRequest = [function (data) {
            return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
        }];

    });

    /**
     * Toast
     */
    shopModule.factory('Toast', function () {
        var returnFunction = null;
        var Modal = function (options) {
            var _self = this, dialog = null;
            _self.open = function () {
                var toast = new auiToast({});
                switch (options.type) {
                    case "success":
                        toast.success({
                            title:options.title || '提交成功',
                            duration:options.duration
                        }, function () {
                            console.log('sc');
                        });
                        break;
                    case "error":
                        toast.fail({
                            title:options.title || '提交失败',
                            duration:options.duration
                        }, function () {
                            console.log('herererer');
                        });
                        break;
                    case "custom":
                        toast.custom({
                            title:options.title || '',
                            duration:options.duration,
                            html: options.html
                        }, function () {
                            console.log('here');
                        });
                        break;
                    case "loading":
                        toast.loading({
                            title:options.title || '加载中',
                            duration:options.duration,
                        });
                        break;
                    case "stop":
                        toast.hide();
                        break;
                }

                if (options.callback) {
                    setTimeout(function () {
                        options.callback();
                    }, options.duration);
                }
            }

        };

        var simpleModal = function (params, type) {
            var title, html, modal, callback, duration = 2000;
            if (typeof params === 'string') {
                title = params || '';
                html = '';
            } else {
                title = params.title || '';
                html = params.html ? params.html : '';
            }

            modal = new Modal({
                type: type,
                title: title,
                html: html,
                duration: duration,
                callback: params.callback || null
            });
            return modal.open();
        };
        returnFunction = function (data) {
            return new Modal(data);
        };
        returnFunction.success = function (params) {
            params = params || {};
            return simpleModal(params, 'success');
        };
        returnFunction.error = function (params) {
            params = params || {};
            return simpleModal(params, 'error');
        };
        returnFunction.custom = function (params) {
            params = params || {};
            return simpleModal(params, 'custom');
        };
        returnFunction.stop = function (params) {
            params = params || {};
            return simpleModal(params, 'stop');
        };
        returnFunction.loading = function (params) {
            params = params || {};
            return simpleModal(params, 'loading');
        };
        return returnFunction;
    });

    /**
     * 模态框
     */
    shopModule.factory('Modal', function () {
        var returnFunction = null;
        var Modal = function (options) {
            var _self = this, dialog = null;
            _self.open = function () {
                var buttons = [], events = [];
                var dialog = new auiDialog({})
                var len = options.buttons && options.buttons.length ? options.buttons.length : 0;
                if (len !== 0) {
                    for (var i=0; i < len; i++) {
                        buttons.push(options.buttons[i].name);
                        if (options.buttons[i].event) {
                            events[i+1] = options.buttons[i].event;
                        } else {
                            events[i+1] = function() {};
                        }
                    }
                } else {
                    buttons = ['确定'];
                    events[1] = function () {}
                }

                function exeEvents(index) {
                    events[index]();
                }

                var info = {
                    title: options.title,
                    msg: options.content,
                    buttons: buttons
                };

                dialog.alert(info,function(ret){
                    exeEvents(ret.buttonIndex);
                })
            }

        };

        var simpleModal = function (params, type) {
            var title, content, buttons, modal;
            if (typeof params === 'string') {
                title = params;
                content = '';
            } else {
                title = params.title;
                content = params.content;
                buttons = params.buttons
            }

            modal = new Modal({
                type: type,
                title: title,
                content: content,
                buttons: buttons
            });
            return modal.open();
        };
        returnFunction = function (data) {
            return new Modal(data);
        };
        returnFunction.alert = function (params) {
            return simpleModal(params, 'alert');
        };
        return returnFunction;
    });

    // 将其注册成 window 对象
    window.sm = shopModule;

}());

function GetQueryString(name)
{
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}

function wordCount(str) {
    return str ? Math.ceil(str.replace(/[\u1000-\uffff]{1}/g, 'aa').length / 2) : 0;
};